package com.rc.fragment;

import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rc.activity.AddExpenseToTrip;
import com.rc.activity.R;
import com.rc.activity.ReceiptBox;
import com.rc.activity.ReceiptBox.OnBackPressedListener;
import com.rc.activity.ReceiptBox.OnOpenSliding;
import com.rc.activity.TripEdit;
import com.rc.activity.dao.tbl_Category;
import com.rc.activity.dao.tbl_CategoryDao;
import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_ItemDao;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripItems;
import com.rc.activity.provider.Contract;
import com.rc.adapter.TripDetailAdapter;
import com.rc.db.DatabaseSupport;
import com.rc.util.Util;
import com.telpoo.frame.model.BaseModel;
import com.telpoo.frame.ui.BaseFragment;

@SuppressLint("ValidFragment")
public class TripDetailFragment extends BaseFragment implements
		OnClickListener, OnBackPressedListener, OnOpenSliding {

	private LinearLayout llSubtotal, llTitle, llReportTrip, llAddExpense,
			llLeg, llFuntion;
	private RelativeLayout rlTotal;
	private ImageView imgArrow;
	private boolean isShow = true;
	private View v;
	private tbl_Trip objTrip;
	private ExpandableListView lvTripDetail;
	private boolean isTrip;
	private long mTripID;
	private String mTripKey = "";
	private ReceiptBox receiptBox;
	private MenuFragment menuFragment;
	private TextView txtTripType, txtTripName, txtCountryFrom, txtTimeFrom,
			txtCountryTo, txtTimeTo, txtTotal, txtClaimed, txtApproved, txtLeg;
	private int start, end;
	// 2 biến được dùng để push lại report detail
	private long reportID;
	private String reportKey;

	public TripDetailFragment() {
		super();
	}

	public TripDetailFragment(String mTripKey, long tripID, boolean isTrip,
			long reportID, String reportKey, int start, int end) {
		super();
		this.mTripID = tripID;
		this.isTrip = isTrip;
		this.reportID = reportID;
		this.reportKey = reportKey;
		this.mTripKey = mTripKey;
		this.start = start;
		this.end = end;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = (ViewGroup) inflater.inflate(R.layout.trip_detail, null);

		receiptBox = (ReceiptBox) getActivity();
		receiptBox.setLogo(R.drawable.ic_top_travelexpense);
		receiptBox.setTitle(getString(R.string.trip_detail));
		receiptBox.setBackground(R.color.background_title_trip, getResources());
		receiptBox.setOnBackPressedListener(new TripDetailFragment(mTripKey,
				mTripID, isTrip, reportID, reportKey, start, end));
		receiptBox.setOnOpenSliding(new TripDetailFragment(mTripKey, mTripID,
				isTrip, reportID, reportKey, start, end));

		llSubtotal = (LinearLayout) v.findViewById(R.id.llsubtotal);
		imgArrow = (ImageView) v.findViewById(R.id.imgArrow);
		rlTotal = (RelativeLayout) v.findViewById(R.id.rlTotal);
		llTitle = (LinearLayout) v.findViewById(R.id.llTitle);
		llReportTrip = (LinearLayout) v.findViewById(R.id.llReportTrip);
		llFuntion = (LinearLayout) v.findViewById(R.id.llFuntion);
		llLeg = (LinearLayout) v.findViewById(R.id.llLeg);
		lvTripDetail = (ExpandableListView) v
				.findViewById(R.id.lvGroupTripDetail);
		llAddExpense = (LinearLayout) v.findViewById(R.id.llAddExpense);
		txtTripType = (TextView) v.findViewById(R.id.txtTripType);
		txtTripName = (TextView) v.findViewById(R.id.txtTripName);
		txtCountryFrom = (TextView) v.findViewById(R.id.txtCountryFrom);
		txtTimeFrom = (TextView) v.findViewById(R.id.txtTimeFrom);
		txtCountryTo = (TextView) v.findViewById(R.id.txtCountryTo);
		txtTotal = (TextView) v.findViewById(R.id.txtTotal);
		txtTimeTo = (TextView) v.findViewById(R.id.txtTimeTo);
		txtClaimed = (TextView) v.findViewById(R.id.txtClaimed);
		txtApproved = (TextView) v.findViewById(R.id.txtApproved);
		txtLeg = (TextView) v.findViewById(R.id.txtLeg);

		llAddExpense.setOnClickListener(this);
		rlTotal.setOnClickListener(this);
		imgArrow.setOnClickListener(this);
		llSubtotal.setOnClickListener(this);
		llTitle.setOnClickListener(this);
		llReportTrip.setOnClickListener(this);
		return v;
	}

	@Override
	public void onResume() {
		super.onResume();
		menuFragment = new MenuFragment();
		objTrip = new tbl_Trip();
		objTrip = DatabaseSupport.getTripByID(mTripID, getActivity());

		String mTripType = objTrip.getType();
		if (getString(R.string.current_trips).equals(mTripType)) {
			txtTripType.setText("C");
		} else if (getString(R.string.past_trips).equals(mTripType)) {
			txtTripType.setText("P");
		} else if (getString(R.string.upcoming_trips).equals(mTripType)) {
			txtTripType.setText("U");
		}

		// nếu trip thuộc report thì sẽ không tồn tại hành động trip to report
		if (objTrip.getReport_ID() > 0) {
			llReportTrip.setVisibility(View.GONE);
		} else {
			llReportTrip.setVisibility(View.VISIBLE);
		}

		// tinh approved theo trip item
		ArrayList<tbl_TripItems> arrTripItem = new ArrayList<tbl_TripItems>();
		float claimed = 0, approved = 0;

		if (objTrip.getReport_ID() != 0) {
			arrTripItem = DatabaseSupport.getTripItemsByTripID(
					objTrip.getTripID(), getActivity());
			for (tbl_TripItems objTripItem : arrTripItem) {
				claimed = claimed + objTripItem.getClaimed();
				approved = approved + objTripItem.getApproved();
			}
		}
		txtApproved.setText("$"
				+ Util.formatStringFloat(Util.convertFloat(approved + "")));
		txtClaimed.setText("$"
				+ Util.formatStringFloat(Util.convertFloat(claimed + "")));

		// tinh total
		txtTotal.setText("$"
				+ Util.formatStringFloat(Util.convertFloat(objTrip.getAmount())));
		txtTripName.setText(objTrip.getName());
		txtCountryFrom.setText(objTrip.getDeparture());
		txtCountryTo.setText(objTrip.getArrival());
		txtTimeFrom.setText(objTrip.getStartDate());
		txtTimeTo.setText(objTrip.getEndDate());
		if (!"".equals(objTrip.getTripLeg())) {
			txtLeg.setText("Leg " + objTrip.getTripLeg());
			llLeg.setVisibility(View.VISIBLE);
		}

		String categories = objTrip.getCategories();
		ArrayList<String> arrParens = new ArrayList<String>();
		String[] cateStrings = null;
		if (categories != null) {
			if (categories.indexOf(",") >= 0) {
				cateStrings = categories.split(",");
				for (String string : cateStrings) {
					arrParens.add(string);
				}
			} else {
				if (!"false".equals(categories)) {
					arrParens.add(categories);
				}
			}
		}

		// show llAddExpense if trip belong to report which draft report
		if (DatabaseSupport.check_editTrip(mTripID, getActivity())) {
			llFuntion.setVisibility(View.VISIBLE);
		} else {
			llFuntion.setVisibility(View.GONE);
		}

		if (arrParens.size() > 0) {
			ArrayList<HashMap<String, ArrayList<tbl_Item>>> arrHmItems = new ArrayList<HashMap<String, ArrayList<tbl_Item>>>();
			HashMap<String, ArrayList<tbl_Item>> hmItems = new HashMap<String, ArrayList<tbl_Item>>();
			ArrayList<tbl_Category> arrCategoryAdd = new ArrayList<tbl_Category>();
			ArrayList<tbl_Item> arrItem = new ArrayList<tbl_Item>();
			for (String string : arrParens) {
				Cursor cursor = getActivity().getContentResolver().query(
						Contract.CONTENT_URI_ITEMS,
						null,
						tbl_ItemDao.Properties.CategoryID.columnName + " = '"
								+ string + "' and "
								+ tbl_ItemDao.Properties.TripID.columnName
								+ " = '" + objTrip.getTripID() + "'", null,
						null);

				arrItem = tbl_Item.getObjectbyCursor(cursor);
				cursor = getActivity().getContentResolver().query(
						Contract.CONTENT_URI_CATEGORY,
						null,
						tbl_CategoryDao.Properties.CategoryID.columnName
								+ " = '" + string + "'", null, null);
				ArrayList<tbl_Category> arrCategory = new ArrayList<tbl_Category>();
				arrCategory = tbl_Category.getObjectbyCursor(cursor);
				for (tbl_Category objCategory : arrCategory) {
					hmItems.put(objCategory.getName(), arrItem);
					arrCategoryAdd.add(objCategory);
				}

				arrHmItems.add(hmItems);
			}

			final TripDetailAdapter adpTrip = new TripDetailAdapter(
					arrCategoryAdd, arrHmItems, objTrip.getReportStatus());
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			adpTrip.setInflater(inflater, getActivity());
			lvTripDetail.setAdapter(adpTrip);
			lvTripDetail.setOnGroupClickListener(new OnGroupClickListener() {

				@Override
				public boolean onGroupClick(ExpandableListView parent, View v,
						int groupPosition, long id) {

					// thay doi image view khi explan
					v = adpTrip.getGroupView(groupPosition, true, v, parent);
					ImageView imgView_down = (ImageView) v
							.findViewById(R.id.imgView_down);
					ImageView imgView_up = (ImageView) v
							.findViewById(R.id.imgView_up);
					if (imgView_down.getVisibility() == View.GONE) {
						imgView_down.setVisibility(View.VISIBLE);
						imgView_up.setVisibility(View.GONE);
					} else {
						imgView_down.setVisibility(View.GONE);
						imgView_up.setVisibility(View.VISIBLE);
					}
					return false;
				}
			});
		}

	}

	private void animation(boolean isShow) {
		Animation animation = null;
		if (isShow) {
			animation = (Animation) AnimationUtils.loadAnimation(getActivity(),
					R.anim.phone_in_bottom_animation);
			llSubtotal.setVisibility(View.VISIBLE);
			imgArrow.setImageResource(R.drawable.ic_arrow_down);
		} else {
			animation = (Animation) AnimationUtils.loadAnimation(getActivity(),
					R.anim.phone_in_top_animation);
			llSubtotal.setVisibility(View.GONE);
			imgArrow.setImageResource(R.drawable.ic_arrow_up);
		}
		llSubtotal.setAnimation(animation);
		llSubtotal.clearAnimation();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.rlTotal:
			if (isShow) {
				animation(isShow);
				isShow = false;
			} else {
				animation(isShow);
				isShow = true;
			}
			break;
		case R.id.llTitle:
			TripEdit.callIntent(getActivity(), objTrip);
			break;
		case R.id.llReportTrip:
			if (objTrip.getIsCreate().equals("1")) {
				createDialogError();
			} else {
				// String date = "";
				// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				// date = format.format(Calendar.getInstance().getTime());
				// callAsynCallServiceReceipt(objTrip.getTripID() + "", date);
				int idReport = DatabaseSupport.addTripToReport(
						objTrip.getTripID(), getActivity());
				if (idReport != -1) {
					menuFragment.resetMenuList(getResources(), getActivity());
					Util.pushFragmentReceiptBox(new ReportDetailFragment(
							idReport, getString(R.string.draft_reports), 0, 0),
							getActivity(), "2");
				}
			}
			break;
		case R.id.llAddExpense:
			AddExpenseToTrip.callIntent(getActivity(), objTrip.getTripID());
			break;
		default:
			break;
		}
	}

	/**
	 * dialog gá»“m 2 lá»±a chá»�n. user cÃ³ thá»ƒ chá»�n tá»›i pháº§n chá»¥p
	 * áº£nh hoáº·c user cÃ³ thá»ƒ chá»�n tá»›i sdcard
	 */

	private void createDialogError() {
		final Dialog dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);

		LinearLayout llOk, llCancel;
		((TextView) dialog.findViewById(R.id.txtTitle))
				.setText(getString(R.string.message_receipt));
		((TextView) dialog.findViewById(R.id.txtContent))
				.setText(getString(R.string.message_edit_report_one));

		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);

		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);
		llCancel.setVisibility(View.GONE);
		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	@Override
	public void doBack(Activity at) {
		if (isTrip) {
			ReceiptBox.obBackPress = null;
			Util.pushFragmentReceiptBox(new TripFragment(mTripKey, start, end),
					(FragmentActivity) at, "3");
		} else {
			Util.pushFragmentReceiptBox(new ReportDetailFragment(reportID,
					reportKey, 0, 0), (FragmentActivity) at, "2");
		}

	}

	/**
	 * Get BaseModel
	 */

	protected BaseModel getModel() {
		return receiptBox.model;
	}

	@Override
	public void doOpen(Activity at) {
		Util.HidenKeyBoard(at);
	}
}
